package cn.xinzhi.main;

import cn.xinzhi.dao.IDepartmentDao;
import cn.xinzhi.dao.IUserDao;
import cn.xinzhi.entity.Department;
import cn.xinzhi.entity.UserInfo;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class Mybatis_Main {
    public static void main(String[] args) {
        SqlSession ss = null;
        try {
            //用流的方式读取配置文件里的信息
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            //创建sql的会话工厂
            SqlSessionFactory s = new SqlSessionFactoryBuilder().build(is);
            //打开一个新的会话
            ss = s.openSession();
            //通过会话创建接口的代理对象
            IDepartmentDao ide = ss.getMapper(IDepartmentDao.class);
            IUserDao mapper = ss.getMapper(IUserDao.class);
            //---------------查全部---------------
            //调用查询方法
            List<Department> des = ide.getAll();
            for (Department si: des) {
                System.out.println(si.getOrganization());
            }
            //-------------id查-----------
            Department de = ide.getInfoById(4);
            System.out.println(de.getOrganization());
            //-------------账号密码查---------
            Department de1 = ide.getInfoName(111,"sdsd");
            System.out.println(de1.getOrganization());
            //-------查总记录数--------
            int count = ide.getCount();
            System.out.println(count);
            //--------增加用户--------
            UserInfo userInfo = new UserInfo();
            userInfo.setUsername("hhhddf");
            userInfo.setPassword("jidja");
            int aa = mapper.addUser(userInfo);
            System.out.println(aa > 0 ? "成功":"失败");
            //提交事物
            ss.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(ss!=null){
                ss.close();
            }
        }
    }
}
